#!/bin/bash

# 检查是否提供了至少一个参数
if [ $# -lt 1 ]; then
    echo "Usage: $0 <branch A> [branch B]"
    exit 1
fi

# 获取参数
branch_A=$1
branch_B=$2

# 遍历当前目录下的所有子目录
for dir in */; do
    # 进入子目录
    cd "$dir" || continue

    # 检查该目录是否是一个Git仓库
    if [ -d ".git" ]; then
        echo "Processing Git repository in $dir"

        # 获取当前分支名称，如果没有提供分支B
        if [ -z "$branch_B" ]; then
            branch_B=$(git symbolic-ref --short -q HEAD)
            if [ $? -ne 0 ]; then
                echo "Failed to get current branch in $dir"
                cd ..
                continue
            fi
            echo "Current branch is $branch_B"
        fi

        # 获取并更新分支A
        git fetch origin "$branch_A"
        if [ $? -ne 0 ]; then
            echo "Failed to fetch branch $branch_A in $dir"
            cd ..
            continue
        fi

        # 获取并更新分支B
        git fetch origin "$branch_B"
        if [ $? -ne 0 ]; then
            echo "Failed to fetch branch $branch_B in $dir"
            cd ..
            continue
        fi

        # 切换到分支B
        git checkout "$branch_B"
        if [ $? -ne 0 ]; then
            echo "Failed to checkout branch $branch_B in $dir"
            cd ..
            continue
        fi

        # 合并分支A到分支B
        git merge origin/"$branch_A"
        if [ $? -ne 0 ]; then
            echo "Failed to merge branch $branch_A into $branch_B in $dir"
        else
            echo "Successfully merged branch $branch_A into $branch_B in $dir"
        fi
    else
        echo "$dir is not a Git repository"
    fi

    # 返回上一级目录
    cd ..
done

echo "All done!"
